package com.industrial.system.aware;

import com.industrial.system.domain.SysArea;
import com.industrial.system.mapper.SysAreaMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>
 *     此类的作用是在SpringBoot启动完成后<br/>
 *     将行政区划数据加载到Redis缴存中
 * </p>
 * @author SangGuangCan
 * @since 2024-01-16
 */
@Component
public class AreaDataToRedisAware implements ApplicationContextAware {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private StringRedisTemplate redisTemplate;

    private SysAreaMapper sysAreaMapper;

    private final String areaPrefix = "area:";

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("开始加载行政区数据到Redis");
        //获取StringRedisTemplate对象
        redisTemplate = applicationContext.getBean(StringRedisTemplate.class);
        //获取SysAreaMapper对象
        sysAreaMapper = applicationContext.getBean(SysAreaMapper.class);
        readAreaDataToRedis();
        readAreaDataVKToRedis();
    }

    private void readAreaDataToRedis() {
        List<SysArea> result = sysAreaMapper.selectShanDongProvinceAreaDataList();
        for(SysArea item : result){
            String areaCode = item.getAreaCode();
            String baseName = item.getBaseName();
            if(StringUtils.isNotBlank(areaCode) && StringUtils.isNotBlank(baseName)){
                redisTemplate.opsForValue().set(areaPrefix + areaCode,baseName);
            }
        }
        logger.info("加载行政区数据到Redis中已完成");
    }

    private void readAreaDataVKToRedis() {
        List<SysArea> result = sysAreaMapper.selectShanDongProvinceAreaDataList();
        for(SysArea item : result){
            String areaCode = item.getAreaCode();
            String baseName = item.getBaseName();
            if(StringUtils.isNotBlank(areaCode) && StringUtils.isNotBlank(baseName)){
                redisTemplate.opsForValue().set("areacode:" + baseName,areaCode);
            }
        }
        logger.info("加载行政区数据VK到Redis中已完成");
    }
}
